package com.dzz.sjgl.utils;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * @author KRIC
 */
public class Word2Pdf {
    private static Logger logger = LoggerFactory.getLogger(Word2Pdf.class);

    public static void word2Pdf(String wordFile, String pdfFile) {
        logger.info(wordFile + "开始转换！");
        // 打开word
        ActiveXComponent app = null;
        Dispatch document = null;
        Dispatch documents = null;
        try {
            app = new ActiveXComponent("Word.Application");
            // 设置word不可见
            app.setProperty("Visible", false);
//            防止弹窗
            app.setProperty("DisplayAlerts", new Variant(false));

            // 获得word中所有打开的文档
            documents = app.getProperty("Documents").toDispatch();
            // 打开文档
            document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
            // 如果文件存在的话，不会覆盖，会直接报错，所以我们需要判断文件是否存在
            File target = new File(pdfFile);
            if (target.exists()) {
                logger.info("该文件已经存在！开始覆盖！");
                target.getAbsoluteFile().delete();
            }
            // 另存为，将文档保存为pdf，其中word保存为pdf的格式宏的值是17
            Dispatch.call(document, "SaveAs", pdfFile, 17);
            logger.info(wordFile + "转换成功！" + pdfFile);
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.error("转换pdf异常");
        } finally {
            // 关闭文档
            Dispatch.call(document, "Close", false);
            document.safeRelease();
            documents.safeRelease();
            // 关闭office
            app.invoke("Quit", 0);
            app.safeRelease();
            //如果没有这句话,winword.exe进程将不会关闭
            ComThread.Release();
        }

    }
}